
package demo.hms.util;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import static org.apache.logging.log4j.message.MapMessage.MapFormat.JSON;

/**
 * Token拦截器配置类，用于处理请求前后的身份验证和状态跟踪
 * @Configuration 标识为Spring配置类
 */
@Configuration
public class TokenInterceptor implements HandlerInterceptor {
    private long refreshTime = 1000 * 60 * 60 * 3;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return true;
////        获取session中的token
//        System.out.println("请求拦截完成，进行拦截判断是不是user登录");
//        HttpSession session = request.getSession();
//        String userId = (String) session.getAttribute("userId") ;
//        System.out.println(userId);
//        if (userId == null || userId.equals("")) {
//            //TODO 登录失败
//            return false;
//        }
//        Map<String,Object> map = new HashMap<>();
//        map = Toekn.parseToken(session.getAttribute("token").toString());
//        if (!userId.equals(map.get("userId"))) {
//            //TODO 登录参数错误
//            returnJson(response,ResultSubmit.error("登录参数错误").toString());
//            return false;
//        }
//
//        long time = (long) map.get("time");
//        long times = System.currentTimeMillis() - time;
//       if (times<refreshTime){
//           System.out.println("登录成功");
//           return true;
//
//       }else {
//           returnJson(response,ResultSubmit.error("登录超时，请重新登录").toString());
//           return false;
//
////           private String JSONCreate(String message){
////               StringBuffer stringBuffer = new StringBuffer();
////               stringBuffer.append("{\"code\":-1,\"message\":\"");
////               stringBuffer.append(message);
////               stringBuffer.append("\"}");
////               return stringBuffer.toString();
////           }
//       }

//        /* 用户身份验证逻辑 */
//        System.out.println(request.getAttribute("user"));
//        if(session.getAttribute("user") == null ) return true;
//        if( session.getAttribute("user").toString() != "user"){
//            return false;
//        }
//
//        /* Token验证流程 */
//        String token = session.getAttribute("token").toString();
//        System.out.println("拦截器获取的token为:"+token);
//        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        System.out.println("业务执行完成，无异常，已放行");
//        HttpSession session = request.getSession();
//        String userId = (String) session.getAttribute("userId") ;
//        String userPassword = (String) session.getAttribute("userPassword") ;
//        String roleName = (String) session.getAttribute("roleName") ;
//        Long time = System.currentTimeMillis();
//        session.setAttribute("time",time);
//        session.setAttribute("token",Toekn.getToken(userId,userPassword,roleName,time));
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("视图渲染完成");
    }

    private void returnJson(HttpServletResponse response, String result) throws Exception {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(result);

        } catch (IOException e) {
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

}
